<html>
<head>
<link rel="shortcut icon" href="./favicon.ico">
<link rel="stylesheet" type="text/css" href="./style.css">
<link rel="canonical" href="./word_pad_function.html">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="When you want to either group a number of words into a larger bit vector, or split a bit vector into a number of smaller words, given the width of a bit vector and the width of a word, returns the number of unused bits at the end of the last word which must be filled with a pad value (usually zero). Handles case where the word width is larger than the bit vector width.">
<title>word pad function</title>
</head>
<body>

<p class="inline bordered"><b><a href="./word_pad_function.vh">Source</a></b></p>
<p class="inline bordered"><b><a href="./legal.html">License</a></b></p>
<p class="inline bordered"><b><a href="./index.html">Index</a></b></p>

<h1>Number of pad bits to fill an incomplete word</h1>
<p>When you want to either group a number of words into a larger bit vector, or
 split a bit vector into a number of smaller words, given the width of a bit
 vector and the width of a word, returns the number of unused bits at the end
 of the last word which must be filled with a pad value (usually zero).
 Handles case where the word width is larger than the bit vector width.</p>
<p><strong>NOTE:</strong> since zero-width values cannot exist in Verilog, if no pad bits
 are needed, this function returns <code>word_width</code> instead of 0. This case
 cannot normally happen (a pad width is maximum <code>word_width-1</code> and minimum
 0), so you can selectively instantiate the pad by checking if the return
 value of this function is equal to <code>word_width</code>, like so:</p>
<pre>
localparam PAD_WIDTH = word_pad(bit_vector_width, word_width);
localparam PAD       = {PAD_WIDTH{1'b0}};

if (PAD_WIDTH != word_width) begin
    baz = {PAD, wibble, ....};
end
else begin
    baz = {wibble, ... };
end
</pre>

<p>If you do not need to create a pad, but only need to index to its location,
 you must externally re-convert a <code>word_width</code> return value back to 0.</p>
<p>Pass the function values which, at elaboration time, are either constants
 or expressions which evaluate to a constant. Then use the return value as an
 integer for a localparam, genvar, etc...</p>
<p>Since this is an included file, it must be idempotent. (defined only once globally)</p>

<pre>
`ifndef WORDPAD_FUNCTION
`define WORDPAD_FUNCTION

function integer word_pad;
    input integer bit_vector_width;
    input integer word_width;
    begin
        word_pad = (bit_vector_width < word_width) ? word_width - bit_vector_width : word_width - (bit_vector_width % word_width);
    end
endfunction

`endif
</pre>

<hr>
<p><a href="./index.html">Back to FPGA Design Elements</a>
<center><a href="https://fpgacpu.ca/">fpgacpu.ca</a></center>
</body>
</html>

